package org.example;
import javafx.animation.PauseTransition;
import javafx.application.Platform;
import javafx.concurrent.Worker;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.image.WritableImage;
import javafx.scene.web.WebView;
import javafx.util.Duration;
import tech.tablesaw.plotly.Plot;
import tech.tablesaw.plotly.components.Figure;
import tech.tablesaw.plotly.components.Page;
import tech.tablesaw.plotly.display.Browser;

import javax.imageio.ImageIO;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 将Tablesaw Figure转换为图片的工具类
 */
public class FigureToImageConverter {

    /**
     * 将Figure转换为图片文件
     * @param figure Tablesaw Figure对象
     * @param outputFile 输出图片文件
     * @param width 图片宽度
     * @param height 图片高度
     * @param format 图片格式(png, jpg等)
     * @return 是否转换成功
     * @throws InterruptedException 如果线程被中断
     */
    public static boolean convertToImage(Figure figure, File outputFile,
                                         int width, int height, String format)
            throws InterruptedException {

        // JavaFX需要在一个单独的线程中运行
        if (!Platform.isFxApplicationThread()) {
            // 确保JavaFX平台已启动
            AtomicBoolean toolkitInitialized = new AtomicBoolean(false);
            CountDownLatch latch = new CountDownLatch(1);

            Platform.startup(() -> {
                toolkitInitialized.set(true);
                latch.countDown();
            });

            latch.await();
            if (!toolkitInitialized.get()) {
                return false;
            }
        }

        // 创建临时HTML文件
        File tempHtml = createTempHtml(figure, "tmp.html");
        if (tempHtml == null) {
            return false;
        }

        // 用于等待截图完成的锁
        CountDownLatch screenshotLatch = new CountDownLatch(1);
        AtomicBoolean success = new AtomicBoolean(false);

        // 在JavaFX应用线程中执行截图操作

        Platform.runLater(() -> {
            WebView webView = new WebView();
            webView.setPrefSize(width, height);
            webView.getEngine().setJavaScriptEnabled(true);
            try {
                webView.getEngine().getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
                    if (newState == Worker.State.SUCCEEDED) {
                        PauseTransition pause = new PauseTransition(Duration.seconds(1)); // 1秒延迟
                        pause.setOnFinished(event -> {
                            try {
                                WritableImage image = new WritableImage(width, height);
                                webView.snapshot(null, image);
                                ImageIO.write(SwingFXUtils.fromFXImage(image, null), format, outputFile);
                                success.set(true);
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                screenshotLatch.countDown();
                                tempHtml.delete();
                            }
                        });
                        pause.play();
                    }
                });

                webView.getEngine().load(tempHtml.toURI().toURL().toExternalForm());
            } catch (Exception e) {
                e.printStackTrace();
                screenshotLatch.countDown();
            }
        });
        screenshotLatch.await();

        return success.get();
    }

    /**
     * 创建临时HTML文件
     */
    private static File createTempHtml(Figure figure, String htmlName) {
        File tempFile = new File(htmlName);
//            tempFile.deleteOnExit();

        // 生成HTML内容
        write(figure, tempFile);

        return tempFile;
    }

    /**
     * 简单使用方法示例
     */
    public static void main(String[] args) throws Exception {
//
//        Figure[] charts = IMRControlChart.getChats(new String[]{});
//        // 示例: 创建一个简单的图表
//        Figure figure = charts[0];// 你的Figure创建代码
//
//        try {
//            boolean success = convertToImage(
//                    figure,
//                    new File("output.png"),
//                    800,
//                    600,
//                    "png"
//            );
//
//            if (success) {
//                System.out.println("图片转换成功!");
//            } else {
//                System.out.println("图片转换失败!");
//            }
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } finally {
//            // 退出JavaFX平台
//            Platform.exit();
//        }
    }

    protected static final String DEFAULT_DIV_NAME = "target";

    public static void write(Figure figure, File outputFile) {
        write(figure, DEFAULT_DIV_NAME, outputFile);
    }


    public static void write(Figure figure, String divName, File outputFile) {
        Page page = Page.pageBuilder(figure, divName).plotlyJsLocation("./plotly-latest.min.js").build();
        String output = page.asJavascript();

        try {
            try (Writer writer =
                         new OutputStreamWriter(new FileOutputStream(outputFile), StandardCharsets.UTF_8)) {
                writer.write(output);
            }
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

}